import os
from osgeo import gdal, gdalconst


def write_tif(file_path, data, geotransform, projection, nodata, dataType):
    gdal_type = ''
    if dataType == 'int16':
        gdal_type = gdal.GDT_Int16
    elif dataType == 'int32':
        gdal_type = gdal.GDT_Int32
    elif dataType == 'float32':
        gdal_type = gdal.GDT_Float32
    elif dataType == 'float64':
        gdal_type = gdal.GDT_Float64
    elif dataType == 'byte':
        gdal_type = gdal.GDT_Byte
    elif dataType == 'uint16':
        gdal_type = gdal.GDT_UInt16
    elif dataType == 'uint32':
        gdal_type = gdal.GDT_UInt32
    driver = gdal.GetDriverByName("GTiff")
    rows, cols = data.shape
    dataset = driver.Create(file_path, cols, rows, 1, gdal_type)
    dataset.SetGeoTransform(geotransform)
    # 定义投影
    # prj = osr.SpatialReference()
    # prj.ImportFromEPSG(4326)
    dataset.SetProjection(projection)
    band = dataset.GetRasterBand(1)
    band.WriteArray(data)
    band.SetNoDataValue(nodata)
    del dataset
    print("写入成功：{}".format(file_path))


# 将evi数据读取并重投影为WGS84坐标系
def evi2tif(hdf_file, tif_dir):
    # 读取hdf文件
    # datasets = gdal.Open(hdf_file)
    # # print(datasets)
    # #  获取hdf中的子数据集
    # SubDatasets = datasets.GetSubDatasets()
    # dataset = gdal.Open(SubDatasets[0][0])
    # geotransform = dataset.GetGeoTransform()
    # #  获取子数据集的个数
    # SubDatasetsNum = len(datasets.GetSubDatasets())
    # print("子数据集一共有{0}个: ".format(SubDatasetsNum))
    # for i in range(SubDatasetsNum):
    #     print(datasets.GetSubDatasets()[i])
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days NDVI"', '[1200x1200] 1 km 16 days NDVI MODIS_Grid_16DAY_1km_VI (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days EVI"', '[1200x1200] 1 km 16 days EVI MODIS_Grid_16DAY_1km_VI (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days VI Quality"', '[1200x1200] 1 km 16 days VI Quality MODIS_Grid_16DAY_1km_VI (16-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days red reflectance"', '[1200x1200] 1 km 16 days red reflectance MODIS_Grid_16DAY_1km_VI (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days NIR reflectance"', '[1200x1200] 1 km 16 days NIR reflectance MODIS_Grid_16DAY_1km_VI (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days blue reflectance"', '[1200x1200] 1 km 16 days blue reflectance MODIS_Grid_16DAY_1km_VI (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days MIR reflectance"', '[1200x1200] 1 km 16 days MIR reflectance MODIS_Grid_16DAY_1km_VI (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days view zenith angle"', '[1200x1200] 1 km 16 days view zenith angle MODIS_Grid_16DAY_1km_VI (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days sun zenith angle"', '[1200x1200] 1 km 16 days sun zenith angle MODIS_Grid_16DAY_1km_VI (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days relative azimuth angle"', '[1200x1200] 1 km 16 days relative azimuth angle MODIS_Grid_16DAY_1km_VI (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days composite day of the year"', '[1200x1200] 1 km 16 days composite day of the year MODIS_Grid_16DAY_1km_VI (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\MOD13A2\\h26v05\\MOD13A2.A2014193.h26v05.061.2021259111900.hdf":MODIS_Grid_16DAY_1km_VI:"1 km 16 days pixel reliability"', '[1200x1200] 1 km 16 days pixel reliability MODIS_Grid_16DAY_1km_VI (8-bit integer)')

    dataset = gdal.Open(r'HDF4_EOS:EOS_GRID:"{}":MODIS_Grid_16DAY_1km_VI:"1 km 16 days EVI"'.format(hdf_file))
    nodata = dataset.GetRasterBand(1).GetNoDataValue()
    if not os.path.exists(tif_dir + "/EVI"):
        os.mkdir(tif_dir + "/EVI")
    output_evi = tif_dir + "/EVI/" + os.path.splitext(hdf_file.split("\\")[-1])[0] + "_evi.tif"
    gdal.Warp(output_evi, dataset, dstSRS='EPSG:4326', srcNodata=nodata, dstNodata=nodata, resampleAlg=gdalconst.GRA_NearestNeighbour)
    dataset = gdal.Open(r'HDF4_EOS:EOS_GRID:"{}":MODIS_Grid_16DAY_1km_VI:"1 km 16 days pixel reliability"'.format(hdf_file))
    nodata = dataset.GetRasterBand(1).GetNoDataValue()
    if not os.path.exists(tif_dir + "/PR"):
        os.mkdir(tif_dir + "/PR")
    output_pr = tif_dir + "/PR/" + os.path.splitext(hdf_file.split("\\")[-1])[0] + "_pr.tif"
    gdal.Warp(output_pr, dataset, dstSRS='EPSG:4326', srcNodata=nodata, dstNodata=nodata, resampleAlg=gdalconst.GRA_NearestNeighbour)
    dataset = gdal.Open(r'HDF4_EOS:EOS_GRID:"{}":MODIS_Grid_16DAY_1km_VI:"1 km 16 days VI Quality"'.format(hdf_file))
    nodata = dataset.GetRasterBand(1).GetNoDataValue()
    if not os.path.exists(tif_dir + "/QC"):
        os.mkdir(tif_dir + "/QC")
    output_qc = tif_dir + "/QC/" + os.path.splitext(hdf_file.split("\\")[-1])[0] + "_qc.tif"
    gdal.Warp(output_qc, dataset, dstSRS='EPSG:4326', srcNodata=nodata, dstNodata=nodata, resampleAlg=gdalconst.GRA_NearestNeighbour)
    dataset = None


# 将evi数据读取并重投影为WGS84坐标系
def lst2tif(hdf_file, tif_dir):
    # 读取hdf文件
    datasets = gdal.Open(hdf_file)
    # print(datasets)
    #  获取hdf中的子数据集
    SubDatasets = datasets.GetSubDatasets()
    dataset = gdal.Open(SubDatasets[0][0])
    geotransform = dataset.GetGeoTransform()
    #  获取子数据集的个数
    SubDatasetsNum = len(datasets.GetSubDatasets())
    print("子数据集一共有{0}个: ".format(SubDatasetsNum))
    for i in range(SubDatasetsNum):
        print(datasets.GetSubDatasets()[i])

    #  获取hdf中的元数据
    Metadata = datasets.GetMetadata()
    #  获取元数据的个数
    MetadataNum = len(Metadata)
    #  输出各子数据集的信息
    print("元数据一共有{0}个: ".format(MetadataNum))
    for key, value in Metadata.items():
        print('{key}:{value}'.format(key=key, value=value))


    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:LST_Day_1km', '[1200x1200] LST_Day_1km MODIS_Grid_Daily_1km_LST (16-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:QC_Day', '[1200x1200] QC_Day MODIS_Grid_Daily_1km_LST (8-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:Day_view_time', '[1200x1200] Day_view_time MODIS_Grid_Daily_1km_LST (8-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:Day_view_angl', '[1200x1200] Day_view_angl MODIS_Grid_Daily_1km_LST (8-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:LST_Night_1km', '[1200x1200] LST_Night_1km MODIS_Grid_Daily_1km_LST (16-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:QC_Night', '[1200x1200] QC_Night MODIS_Grid_Daily_1km_LST (8-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:Night_view_time', '[1200x1200] Night_view_time MODIS_Grid_Daily_1km_LST (8-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:Night_view_angl', '[1200x1200] Night_view_angl MODIS_Grid_Daily_1km_LST (8-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:Emis_31', '[1200x1200] Emis_31 MODIS_Grid_Daily_1km_LST (8-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:Emis_32', '[1200x1200] Emis_32 MODIS_Grid_Daily_1km_LST (8-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:Clear_day_cov', '[1200x1200] Clear_day_cov MODIS_Grid_Daily_1km_LST (16-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\0728\\MOD11A1.A2013209.h25v05.006.2016163091102.hdf":MODIS_Grid_Daily_1km_LST:Clear_night_cov', '[1200x1200] Clear_night_cov MODIS_Grid_Daily_1km_LST (16-bit unsigned integer)')

    dataset = gdal.Open(r'HDF4_EOS:EOS_GRID:"{}":MODIS_Grid_Daily_1km_LST:LST_Day_1km'.format(hdf_file))
    nodata = dataset.GetRasterBand(1).GetNoDataValue()
    if not os.path.exists(tif_dir + "/LST_day"):
        os.mkdir(tif_dir + "/LST_day")
    output_lst = tif_dir + "/LST_day/" + os.path.splitext(hdf_file.split("\\")[-1])[0] + "_LST_Day_1km.tif"
    gdal.Warp(output_lst, dataset, dstSRS='EPSG:4326', srcNodata=nodata, dstNodata=nodata, resampleAlg=gdalconst.GRA_NearestNeighbour)
    dataset = gdal.Open(r'HDF4_EOS:EOS_GRID:"{}":MODIS_Grid_Daily_1km_LST:QC_Day'.format(hdf_file))
    nodata = dataset.GetRasterBand(1).GetNoDataValue()
    if not os.path.exists(tif_dir + "/LST_day_qc"):
        os.mkdir(tif_dir + "/LST_day_qc")
    output_lst = tif_dir + "/LST_day_qc/" + os.path.splitext(hdf_file.split("\\")[-1])[0] + "_QC_Day.tif"
    gdal.Warp(output_lst, dataset, dstSRS='EPSG:4326', srcNodata=nodata, dstNodata=nodata, resampleAlg=gdalconst.GRA_NearestNeighbour)
    dataset = gdal.Open(r'HDF4_EOS:EOS_GRID:"{}":MODIS_Grid_Daily_1km_LST:LST_Night_1km'.format(hdf_file))
    nodata = dataset.GetRasterBand(1).GetNoDataValue()
    if not os.path.exists(tif_dir + "/LST_night"):
        os.mkdir(tif_dir + "/LST_night")
    output_lst = tif_dir + "/LST_night/" + os.path.splitext(hdf_file.split("\\")[-1])[0] + "_LST_Night_1km.tif"
    gdal.Warp(output_lst, dataset, dstSRS='EPSG:4326', srcNodata=nodata, dstNodata=nodata, resampleAlg=gdalconst.GRA_NearestNeighbour)
    dataset = gdal.Open(r'HDF4_EOS:EOS_GRID:"{}":MODIS_Grid_Daily_1km_LST:QC_Night'.format(hdf_file))
    nodata = dataset.GetRasterBand(1).GetNoDataValue()
    if not os.path.exists(tif_dir + "/LST_night_qc"):
        os.mkdir(tif_dir + "/LST_night_qc")
    output_lst = tif_dir + "/LST_night_qc/" + os.path.splitext(hdf_file.split("\\")[-1])[0] + "_QC_Night.tif"
    gdal.Warp(output_lst, dataset, dstSRS='EPSG:4326', srcNodata=nodata, dstNodata=nodata, resampleAlg=gdalconst.GRA_NearestNeighbour)
    dataset = None


def glass2tif(hdf_file, tif_dir):
    # 读取hdf文件
    # datasets = gdal.Open(hdf_file)
    # # print(datasets)
    # #  获取hdf中的子数据集
    # SubDatasets = datasets.GetSubDatasets()
    # dataset = gdal.Open(SubDatasets[0][0])
    # geotransform = dataset.GetGeoTransform()
    # #  获取子数据集的个数
    # SubDatasetsNum = len(datasets.GetSubDatasets())
    # print("子数据集一共有{0}个: ".format(SubDatasetsNum))
    # for i in range(SubDatasetsNum):
    #     print(datasets.GetSubDatasets()[i])
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\GLASS\\h25v05\\GLASS02A06.V40.A2013249.h25v05.2017102.hdf":GLASS02A06:ABD_BSA_VIS', '[1200x1200] ABD_BSA_VIS GLASS02A06 (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\GLASS\\h25v05\\GLASS02A06.V40.A2013249.h25v05.2017102.hdf":GLASS02A06:ABD_WSA_VIS', '[1200x1200] ABD_WSA_VIS GLASS02A06 (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\GLASS\\h25v05\\GLASS02A06.V40.A2013249.h25v05.2017102.hdf":GLASS02A06:QC_VIS', '[1200x1200] QC_VIS GLASS02A06 (16-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\GLASS\\h25v05\\GLASS02A06.V40.A2013249.h25v05.2017102.hdf":GLASS02A06:ABD_BSA_NIR', '[1200x1200] ABD_BSA_NIR GLASS02A06 (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\GLASS\\h25v05\\GLASS02A06.V40.A2013249.h25v05.2017102.hdf":GLASS02A06:ABD_WSA_NIR', '[1200x1200] ABD_WSA_NIR GLASS02A06 (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\GLASS\\h25v05\\GLASS02A06.V40.A2013249.h25v05.2017102.hdf":GLASS02A06:QC_NIR', '[1200x1200] QC_NIR GLASS02A06 (16-bit unsigned integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\GLASS\\h25v05\\GLASS02A06.V40.A2013249.h25v05.2017102.hdf":GLASS02A06:ABD_BSA_shortwave', '[1200x1200] ABD_BSA_shortwave GLASS02A06 (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\GLASS\\h25v05\\GLASS02A06.V40.A2013249.h25v05.2017102.hdf":GLASS02A06:ABD_WSA_shortwave', '[1200x1200] ABD_WSA_shortwave GLASS02A06 (16-bit integer)')
    # ('HDF4_EOS:EOS_GRID:"G:\\test\\GLASS\\h25v05\\GLASS02A06.V40.A2013249.h25v05.2017102.hdf":GLASS02A06:QC_shortwave', '[1200x1200] QC_shortwave GLASS02A06 (16-bit unsigned integer)')

    dataset = gdal.Open(r'HDF4_EOS:EOS_GRID:"{}":GLASS02A06:ABD_BSA_VIS'.format(hdf_file))
    nodata = dataset.GetRasterBand(1).GetNoDataValue()
    if not os.path.exists(tif_dir + "/ABD_BSA_VIS"):
        os.mkdir(tif_dir + "/ABD_BSA_VIS")
    output_lst = tif_dir + "/ABD_BSA_VIS/" + os.path.splitext(hdf_file.split("\\")[-1])[0] + "_ABD_BSA_VIS.tif"
    gdal.Warp(output_lst, dataset, dstSRS='EPSG:4326', srcNodata=nodata, dstNodata=nodata, resampleAlg=gdalconst.GRA_NearestNeighbour)
    dataset = gdal.Open(r'HDF4_EOS:EOS_GRID:"{}":GLASS02A06:ABD_WSA_VIS'.format(hdf_file))
    nodata = dataset.GetRasterBand(1).GetNoDataValue()
    if not os.path.exists(tif_dir + "/ABD_WSA_VIS"):
        os.mkdir(tif_dir + "/ABD_WSA_VIS")
    output_lst = tif_dir + "/ABD_WSA_VIS/" + os.path.splitext(hdf_file.split("\\")[-1])[0] + "_ABD_WSA_VIS.tif"
    gdal.Warp(output_lst, dataset, dstSRS='EPSG:4326', srcNodata=nodata, dstNodata=nodata, resampleAlg=gdalconst.GRA_NearestNeighbour)
    dataset = gdal.Open(r'HDF4_EOS:EOS_GRID:"{}":GLASS02A06:QC_VIS'.format(hdf_file))
    nodata = dataset.GetRasterBand(1).GetNoDataValue()
    if not os.path.exists(tif_dir + "/QC_VIS"):
        os.mkdir(tif_dir + "/QC_VIS")
    output_lst = tif_dir + "/QC_VIS/" + os.path.splitext(hdf_file.split("\\")[-1])[0] + "_QC_VIS.tif"
    gdal.Warp(output_lst, dataset, dstSRS='EPSG:4326', srcNodata=nodata, dstNodata=nodata, resampleAlg=gdalconst.GRA_NearestNeighbour)
    dataset = None


def main(hdf_dir, tif_dir, type):
    basename = ".hdf"
    file_ls = [os.path.join(hdf_dir, f) for f in os.listdir(hdf_dir) if f.endswith(basename)]

    if type == "LST":
        for hdf_file in file_ls:
            lst2tif(hdf_file, tif_dir)
        print("LST转换完成！")
    elif type == "EVI":
        for hdf_file in file_ls:
            evi2tif(hdf_file, tif_dir)
        print("EVI转换完成！")
    elif type == "GLASS":
        for hdf_file in file_ls:
            glass2tif(hdf_file, tif_dir)
        print("GLASS转换完成！")


if __name__ == '__main__':
    # lst_file = r"G:\test\0728\MOD11A1.A2013209.h25v05.006.2016163091102.hdf"
    # lst2tif(lst_file, r"G:\test\0728")
    # 转换LST
    hdf_dir = r"G:\test\MYD11A1\h26v05"
    tif_dir = r"G:\test\process_result\LST_tif\aqua\h26v05"
    main(hdf_dir, tif_dir, "LST")
    # 转换EVI
    # hdf_dir = r"G:\test\MOD13A2\h26v05"
    # tif_dir = r"G:\test\process_result\EVI_tif\h26v05"
    # main(hdf_dir, tif_dir, "EVI")
    # 转换GLASS
    # hdf_dir = r"G:\test\GLASS\h26v05"
    # tif_dir = r"G:\test\process_result\GLASS_tif\h26v05"
    # main(hdf_dir, tif_dir, "GLASS")
